﻿using System;
using Porownywarka.Interfejsy;

namespace Porownywarka.Sortowanie
{
    public class BubbleSort<T> : ISortMethod<T> 
        where T : IComparable<T>
    {
        public T[] SortedData { get; private set; }

        public T[] Sort(T[] tablica, object l)
        {
            //T[] tabRes = (T[])tablica.Clone();

            T[] tabRes;

            lock(l)
            {
                tabRes = (T[])tablica.Clone();
            }
            
            SortedData = tabRes;
            return Sort(ref tabRes);
        }

        private T[] Sort(ref T[] tabRes)
        {
            for (int i = 0; i < tabRes.Length; i++)
            {

                bool zamiana = false;
                for (int j = tabRes.Length - 1; j > i; j--)
                    if (tabRes[j].CompareTo(tabRes[j - 1]) < 0)
                    {
                        T t = tabRes[j];
                        tabRes[j] = tabRes[j - 1];
                        tabRes[j - 1] = t;
                        zamiana = true;
                    }
                if (!zamiana)
                    break;
            }

            return tabRes;            
        }
    }
}
